package com.yowosoft.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

@Controller
public class TestController {

	@RequestMapping(value = "test", method = RequestMethod.GET)
	@ResponseBody
	public String test() {
		String result = "测试数据asdasdasdas";
		return result;
	}

	@RequestMapping(value = "/testJson", method = RequestMethod.GET)
	public String sentJson(HttpServletResponse response) {
		JsonObject object = new JsonObject();
		object.addProperty("wish", "success");

		JsonArray array = new JsonArray();
		JsonObject list1 = new JsonObject();
		list1.addProperty("id", 1);
		list1.addProperty("name", "java");
		list1.addProperty("age", 9);
		array.add(list1);

		JsonObject list2 = new JsonObject();
		list2.addProperty("id", 2);
		list2.addProperty("name", "C#");
		list2.addProperty("age", 5);
		array.add(list2);

		object.add("people", array);
		// 查看数据
		System.out.println(object);
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		writer.write(new Gson().toJson(object));
		writer.flush();
		writer.close();
		return "hatcher";
	}

	@RequestMapping(value = "/login/{name}", method = RequestMethod.GET) // 用来处理前台的login请求
	private String hello(Model model, @PathVariable("name") String name) {
		model.addAttribute("name", name);
		System.out.println(name);
		return "hatcher";
	}

	@RequestMapping(value = "/page/{name}/{age}", method = RequestMethod.GET)
	public String getName(ModelMap model, @PathVariable("name") String name, @PathVariable("age") int age) {
		model.put("name", name);
		model.put("age", age);
		return "hatcher";
	}

	// 测试成功
	@RequestMapping(value = "/result", method = RequestMethod.GET)
	public String result(ModelMap model, @RequestParam String name, @RequestParam int age) {
		model.addAttribute("name", name);
		model.addAttribute("age", age);
		return "hatcher";

	}

	// 测试成功
	@RequestMapping("/hello")
	public String sayHello(ModelMap map) {
		System.out.println("say Hello ……");
		return "hatcher";
	}

}
